// import "@/assets/js/tracking-min.js";
import "tracking";
import "tracking/build/data/face";
import { ref } from "vue";
import { toFile } from "@/utils/file.js";

export default function useTracking() {
  let video = ref();
  let trackerTask = ref();
  let rets = ref();
  let canvas;

  let trackingTitle = ref("");

  let fileImg = ref();
  let isDetectionFace = ref(false);

  function openCamera() {
    video.value = document.getElementById("video");
    canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");

    let tracker = new window.tracking.ObjectTracker("face");

    tracker.setStepSize(1);
    // 识别率
    tracker.setEdgesDensity(0.08);
    tracker.setInitialScale(5);

    trackerTask.value = window.tracking.track("#video", tracker);

    tracker.on("track", (event) => {
      // console.log(event);
      // 清除画布
      context.clearRect(0, 0, canvas.width, canvas.height);

      fileImg.value = "";

      if (event.data.length === 0) {
        console.log("未检测到人脸");
        trackingTitle.value = "未检测到人脸";
        isDetectionFace.value = false;
      } else if (event.data.length === 1) {
        const rect = event.data[0];
        // event.data.forEach(function (rect) {
        //   console.log(rect);

        //   rets.value = rect;
        //   context.strokeStyle = "#42e365";
        //   context.lineWidth = 2;
        //   context.strokeRect(rect.x, rect.y, rect.width, rect.height);
        // });
        rets.value = rect;
        // 画框框
        context.strokeStyle = "#456bfb";
        context.lineWidth = 2;
        context.strokeRect(rect.x, rect.y, rect.width, rect.height);

        saveImage();

        isDetectionFace.value = true;

        // trackerTask.value.stop();
        // tracker = null;
        // video.value.pause();
      }
    });
  }

  // 保存照片
  function saveImage() {
    let imgcanvas = document.getElementById("imgcanvas");
    let ctx = imgcanvas.getContext("2d");

    imgcanvas.width = 280;
    imgcanvas.height = 280;

    ctx.clearRect(0, 0, imgcanvas.width, imgcanvas.height);

    ctx.drawImage(video.value, 0, 0, 280, 280);
    // 获取图片base64链接
    var image = imgcanvas.toDataURL("image/jpg");

    // imgcanvas.toBlob(async (blob) => {
    //   console.log(blob);
    // });

    fileImg.value = image;
  }

  // 获取照片
  function trackingGetImage(fileName = "img") {
    if (fileImg.value) {
      const imgFile = toFile(fileImg.value, fileName);
      return imgFile;
    } else return;
  }

  // 关闭监听
  function closeListen() {
    if (trackerTask.value) trackerTask.value.stop();
    // if (video.value) video.value.pause();
    if (canvas) {
      const context = canvas.getContext("2d");
      context.clearRect(0, 0, canvas.width, canvas.height);
    }
  }

  return {
    isDetectionFace,
    trackingTitle,
    openCamera,
    trackingGetImage,
    closeListen,
  };
}
